<template>
  <div>
    <!-- <el-tabs v-model="activeTab" @tab-click="handleClick">
      <el-tab-pane label="外部导入镜像" name="first">外部导入镜像</el-tab-pane>
      <el-tab-pane label="手动创建镜像" name="second">手动创建镜像</el-tab-pane>
    </el-tabs> -->
    <div class="form">
      <div>
        <span>镜像名称：</span>
        <el-input v-model="image_name" placeholder="请输入镜像名称" />
      </div>
      <div>
        <span>先择基础镜像源：</span>
        <el-autocomplete
          class="inline-input"
          v-model="selectedImage"
          :fetch-suggestions="queryImage"
          placeholder="请输入镜像名称"
          @select="selectImage"
        ></el-autocomplete>
      </div>

      <div class="dialog-footer">
        <el-button type="primary" @click="onSubmit">{{loading ? '实例创建中...' : '保 存'}}</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {imageModel} from '@/api/models.js'
import { Message } from 'element-ui';
export default {
  data() {
    return {
      activeTab: 'second',
      images: [],
      image: null,
      image_name: '',
      selectedImage: '',
      loading: false
    }
  },
  mounted() {
    this.getList();
  },
  methods: {
    queryImage(queryString, cb) {
      // if(queryString == '') return;
      imageModel.list({
        import_status: 2,
        get_public: 1,
        image_name: queryString
      }, res => {
        let results = res.data.map((v) => {
          return {
            id: v.id,
            value: v.image_name
          }
        })
        cb(results)
      })
    },
    selectImage(item) {
      this.image = item.id
      this.selectedImage = item.value;
    },
    getList() {
      imageModel.list({
        import_status: 2
      }, res => {
        this.images = res.data
      })
    },
    handleClick(tab) {
      if(tab.name == 'first') {
        this.$router.replace('/image/import')
      }
    },
    onSubmit() {
      if (this.loading) return;
      if(!this.image || !this.image_name) {
        return Message.warning('请先选择镜像')
      }
      this.loading = true
      this.open()
      imageModel.create1({
        image_id: this.image
      }, (res) => {
        this.loading = false
        if(res.data.instance_id) {
          this.$router.push('/image/create2/' + res.data.instance_id+'/' + this.image + '?vnc=' + res.data.vnc + '&name=' + this.image_name)
        }
      },err => {
        this.loading = false
        console.log(err)
      })
    },
     open() {
       this.$notify.success({
         title: '制作镜像',
         message: '镜像正在复制中，请您耐心等待^_^',
         showClose: false
       });
     }
  }
}
</script>
<style lang="scss" scoped>
.form{
  text-align: left;
}
#image_source{
  height: 34px;
}
</style>